package cn.yitun.chat.yitunserverimapicore.business.contact.action;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.YitunException;
import cn.yitun.chat.yituncommonmessage.impl.HeadImpl;
import cn.yitun.chat.yituncommonmessage.result.ResultMessage;
import cn.yitun.chat.yituncommonutil.YitunCollectionUtil;
import cn.yitun.chat.yituncommonutil.YitunMapUtil;
import cn.yitun.chat.yitungeneral.annotation.action.ActionMapping;
import cn.yitun.chat.yitungeneral.annotation.parameter.JsonDefine;
import cn.yitun.chat.yitunnetsession.session.SocketSession;
import cn.yitun.chat.yitunservercommonlib.constant.ActionTypeConstant;
import cn.yitun.chat.yitunservercommonlib.converter.dto2vo.user.UserDto2VoConverter;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.contact.ContactAddApplyDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.dto.userchat.ChatDataDto;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.contact.ContactAddApplyVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.contact.ContactAddVerifyAnswerVo;
import cn.yitun.chat.yitunservercommonlib.dataentity.vo.system.user.UserVo;
import cn.yitun.chat.yitunservercommonlib.util.NumUtil;
import cn.yitun.chat.yitunservercommonlib.util.R;
import cn.yitun.chat.yitunserverimapicore.business.contact.service.ContactAddApplyService;
import cn.yitun.chat.yitunserverimapicore.business.contact.service.ContactAddService;
import cn.yitun.chat.yitunserverimapicore.business.contact.service.ContactAddVerifyAnswerService;
import cn.yitun.chat.yitunserverimapicore.business.contact.service.ContactService;
import cn.yitun.chat.yitunserverimapicore.business.user.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * Date 2019-01-20 13:10:36<br>
 * Description
 *
 * @author yitun<br>
 * @version 1.1
 */
@Component
@ActionMapping(value = ActionTypeConstant.CONTACT_ACTION_PUSH)
public class ContactAction {

	@Resource
	private ContactService contactService;
	@Resource
	private ContactAddService contactAddService;
	@Resource
	private ContactAddApplyService contactAddRequestService;
	@Resource
	private ContactAddVerifyAnswerService contactAddVerifyAnswerService;
	@Resource
	private UserService userService;

	@ActionMapping(value = "1.1.0001")
	public ResultMessage count(SocketSession socketSession, @JsonDefine("data") ChatDataDto query) {
		Long ownerUserId = socketSession.getKey();
		query.setOwnerUserId(ownerUserId);
		return new ResultMessage(R.param("count", contactService.countUserDataListByContactCategoryMemberOwnerUserId(query)));
	}

	/**
	 * 
	 * Date 2019-01-20 19:27:50<br>
	 * Description 获取所有联系人信息
	 * 
	 * @param socketSession
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	@ActionMapping(value = "1.1.0002")
	public ResultMessage list(
			SocketSession socketSession, @JsonDefine("data") ChatDataDto query) {
		Long ownerUserId = socketSession.getKey();
		query.setOwnerUserId(ownerUserId);
		PageHelper.startPage(query.getCurrentPageNo(), query.getPageSize());
		List<UserVo> list = contactService.getUserDataListByContactCategoryMemberOwnerUserId(query);
		userService.setUserStatus(UserDto2VoConverter.INSTANCE.vo2dto(list));
		return new ResultMessage(R.param("page", new PageInfo<>(list)));
	}

	/**
	 * 
	 * Date 2019-01-20 19:27:33<br>
	 * Description 获取所有联系人在线状态
	 * @param socketSession
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	@ActionMapping(value = "1.1.0003")
	public ResultMessage getUserDataStatusList(
			SocketSession socketSession,
			@JsonDefine("data") ChatDataDto query) {
		Long ownerUserId = socketSession.getKey();
		query.setOwnerUserId(ownerUserId);
		List<UserVo> contactList = contactService.getUserDataListByContactCategoryMemberOwnerUserId(query);
		userService.setUserStatus(UserDto2VoConverter.INSTANCE.vo2dto(contactList));
		List<Map<String, Object>> list = new ArrayList<>();
		for (UserVo userData : contactList) {
			Map<String, Object> map = new HashMap<>();
			map.put("userId", userData.getId());
			map.put("status", userData.getStatus());
			list.add(map);
		}
		return new ResultMessage(R.param("page", new PageInfo<>(list)));
	}

	/**
	 * 
	 * Date 2019-01-20 18:17:16<br>
	 * Description 获取用户被加为好的权限设置
	 * 
	 * @param query
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	@ActionMapping(value = "1.1.0006")
	public ResultMessage getContactAddVerifySetting (
			SocketSession socketSession,
			@JsonDefine("data") ChatDataDto query) {
		if (NumUtil.isInValid(query.getTargetUserId()))
			throw new YitunException(ExceptionEnum.LOSE_FILED);

		Long applyUserId = socketSession.getKey();
		query.setApplyUserId(applyUserId);
		return contactAddService.getContactAddVerifySetting(query);
	}

	/**
	 * 
	 * Date 2019-01-20 18:17:43<br>
	 * Description 请求添加为好友
	 * 
	 * @param request
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	@ActionMapping(value = "1.1.0007")
	public ResultMessage sendAddApply(
			SocketSession socketSession,
			@JsonDefine("data") ContactAddApplyDto request) {
		ResultMessage message = contactAddService.userAddApply(socketSession.getKey(), request);
		return message;
	}

	/**
	 * 获取请求计数
	 * @param socketSession
	 * @param query
	 * @return
	 */
	@ActionMapping(value = "1.1.0008")
	public ResultMessage getApplyCount(
			SocketSession socketSession,
			@JsonDefine("data") ContactAddApplyDto query) {
		Long ownerUserId = socketSession.getKey();
		query.setTargetUserId(ownerUserId);
		int count = contactAddRequestService.count(YitunMapUtil.java2Map(query, false));
		return new ResultMessage(R.param("count", count));
	}

	/**
	 * 已经接收的请求
	 * @param socketSession
	 * @param query
	 * @return
	 */
	@ActionMapping(value = "1.1.0009")
	public ResultMessage queryApplyReceiveList (
			SocketSession socketSession,
			@JsonDefine("data") ContactAddApplyDto query) {
		Long ownerUserId = socketSession.getKey();
		query.setTargetUserId(ownerUserId);
		List<Long> userIds = new ArrayList<>();
		List<Long> applyIds = new ArrayList<>();
		PageHelper.startPage(query.getCurrentPageNo(), query.getPageSize());
		List<ContactAddApplyVo> applys = contactAddRequestService.queryList(query);
		for (ContactAddApplyVo ap : applys) {
			userIds.add(ap.getApplyUserId());
			applyIds.add(ap.getId());
		}
		Map<Long, UserVo> userMap = new HashMap<>();
		Map<Long, List<ContactAddVerifyAnswerVo>> answerMap = new HashMap<>();

		List<UserVo> users = userService.getUserDataList(userIds);
		List<ContactAddVerifyAnswerVo> answers = contactAddVerifyAnswerService.getListByApplyIds(ownerUserId, applyIds);

		for (UserVo u : users) {
			userMap.put(u.getId(), u);
		}

		for (ContactAddVerifyAnswerVo a : answers) {
			Long aid = a.getApplyId();
			List<ContactAddVerifyAnswerVo> list = answerMap.get(aid);
			if (null == list) {
				list = new ArrayList<>();
				answerMap.put(aid, list);
			}
			list.add(a);
		}

		List<Map<String, Object>> list = new ArrayList<>();

		for (ContactAddApplyVo ap : applys) {
			Long aid = ap.getId();
			Long uid = ap.getApplyUserId();
			Map<String, Object> map = new HashMap<>();

			UserVo user = userMap.get(uid);
			List<ContactAddVerifyAnswerVo> answerList = answerMap.get(aid);
			map.put("apply", ap);
			map.put("user", user);
			map.put("answerList", answerList);

			list.add(map);
		}

		return new ResultMessage(R.param("page", new PageInfo<>(list)));
	}

	@ActionMapping(value = "1.1.0010")
	public ResultMessage queryApplyDataReceiveList(
			SocketSession socketSession,
			@JsonDefine("data") ContactAddApplyDto query) {
		Long ownerUserId = socketSession.getKey();
		query.setTargetUserId(ownerUserId);
		List<Long> userIds = new ArrayList<>();
		List<Long> applyIds = new ArrayList<>();
		PageHelper.startPage(query.getCurrentPageNo(), query.getPageSize());
		List<ContactAddApplyVo> applyList = contactAddRequestService.queryList(query);

        List<Map<String, Object>> list = new ArrayList<>();
		if (YitunCollectionUtil.isNotEmpty(applyList)) {
            for (ContactAddApplyVo ap : applyList) {
                userIds.add(ap.getApplyUserId());
                applyIds.add(ap.getId());
            }

            if (YitunCollectionUtil.isNotEmpty(userIds) && YitunCollectionUtil.isNotEmpty(applyIds)) {
                Map<Long, UserVo> userMap = new HashMap<>();
                Map<Long, List<ContactAddVerifyAnswerVo>> answerMap = new HashMap<>();

                List<UserVo> users = userService.getUserDataList(userIds);
                List<ContactAddVerifyAnswerVo> answers = contactAddVerifyAnswerService.getListByApplyIds(ownerUserId, applyIds);

                for (UserVo u : users) {
                    userMap.put(u.getId(), u);
                }

                for (ContactAddVerifyAnswerVo a : answers) {
                    Long aid = a.getApplyId();
                    List<ContactAddVerifyAnswerVo> answerList = answerMap.get(aid);
					//如果还没有该请求的验证答案，则代入空集，有则添加
					if (null == answerList) {
                        answerList = new ArrayList<>();
                        answerMap.put(aid, answerList);
                    } else {
						answerList.add(a);
					}
                }

                for (ContactAddApplyVo ap : applyList) {
                    Long aid = ap.getId();
                    Long uid = ap.getApplyUserId();
                    Map<String, Object> map = new HashMap<>();

                    UserVo user = userMap.get(uid);
                    List<ContactAddVerifyAnswerVo> answerList = answerMap.get(aid);
                    map.put("apply", ap);
                    map.put("user", user);
                    map.put("answerList", answerList);

                    list.add(map);
                }
            }
        }

		return new ResultMessage(R.param("page", new PageInfo<>(list)));
	}

	@ActionMapping(value = "1.1.0011")
	public ResultMessage getRequest(
			SocketSession socketSession,
			@JsonDefine("data") ChatDataDto query) {
		Long ownerUserId = socketSession.getKey();
		query.setOwnerUserId(ownerUserId);
		ResultMessage message = new ResultMessage();
		ContactAddApplyVo request = contactAddRequestService.getVO(query.getApplyId());
		List<ContactAddVerifyAnswerVo> answerList = contactAddVerifyAnswerService.getListByApplyId(ownerUserId, query.getApplyId());


		message.bodyPut("apply", request);
		message.bodyPut("answerList", answerList);
		if (null != request) {
			UserVo user = userService.getUserDataById(request.getApplyUserId());
			message.bodyPut("user", user);
		}
//			List<ContactAddApplyVo> requestList = contactAddRequestService.listVO(YitunMapUtil.java2Map(query, false));
//			if (YitunCollectionUtil.isNotEmpty(requestList)) {
//				for (ContactAddApplyVo request : requestList) {
//					List<ContactAddVerifyAnswerVo> answerList = contactAddVerifyAnswerService.getListByApplyId(ownerUserId, request.getId());
////					request.set
//					//TODO
//				}
//
//			}

		return message;
	}

	/**
	 * 
	 * Date 2019-01-20 18:18:03<br>
	 * Description 处理被添加请求
	 * 
	 * @param head
	 * @param response
	 * @return
	 * @author yitun<br>
	 * @version 1.1
	 */
	@ActionMapping(value = "1.1.0012")
	public ResultMessage applyHandle(
			HeadImpl head,
			@JsonDefine("data") ContactAddApplyDto response) {
		return contactAddService.userAddResponse(head.getKey(), response);
	}

}
